package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequiredPermission(name = "权限列表",expression = "permission:list")
    public String list(Model model, QueryObject qo){
        model.addAttribute("pageInfo", permissionService.query(qo));
        return "/permission/list";

    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiredPermission(name = "权限删除",expression = "permission:delete")
    public JsonResult delete(Long id){

        try {
            if (id != null) {
                permissionService.delete(id);
            }
            return new JsonResult();//success 默认为true
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }

    }

    @RequestMapping("/reload")
    @ResponseBody
    @RequiredPermission(name = "权限重新加载",expression = "permission:reload")
    public JsonResult reload(){

            permissionService.reload();
            return new JsonResult();

    }


    @RequestMapping("/input")
    public String input(Long id, Model model){
        if (id != null) {
            Permission permission = permissionService.get(id);
            model.addAttribute("permission", permission);
        }
        return "/permission/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission permission){
        if (permission.getId() != null) {
            permissionService.update(permission);
        }
        else {
            permissionService.save(permission);
        }
        return "redirect:/permission/list.do";
    }
}
